import machine
from machine import ADC, Pin,I2C, deepsleep
from machine import RTC
import utime
import esp32
import PFC8563
import lcd12864
import sht31
adc = ADC(Pin(34))
adc.atten(ADC.ATTN_11DB)    # set 11dB input attenuation (voltage range roughly 0.0v - 3.6v)
adc.width(ADC.WIDTH_12BIT)  
led=Pin(12,Pin.OUT)
print(machine.wake_reason())
wake1 = Pin(27, mode = Pin.IN,pull=machine.Pin.PULL_UP)
#level parameter can be: esp32.WAKEUP_ANY_HIGH or esp32.WAKEUP_ALL_LOW
esp32.wake_on_ext0(pin = wake1, level = esp32.WAKEUP_ALL_LOW)
rtc = RTC()

i2c = I2C(1, scl=Pin(18), sda=Pin(19), freq=400000)
def showFast():
    showSlow()
    led.on()
    for i in range(60):

        da=i2c.readfrom_mem(81,2,1)
        s=((da[0]>>4) * 10) + (da[0]&0x0f)
        if(s==0):
            showSlow()
        a=adc.read()
        sht31.sht31m(i2c)
        utime.sleep_ms(50)
        (t,h)=(sht31.sht31r(i2c))
        lcd12864.st1(t,h,a*6.5362/4096)
        lcd12864.print8("%02d   "%(s),80,2)

        t=rtc.datetime()
        print(i)
        utime.sleep_us(1000000-t[7])
        # utime.sleep_us(1000000-t[7])
    lcd12864.print8("     ",80,2)
    led.off()
    machine.deepsleep((60-s)*1000)

def showSlow():
    (s,m,h,d,w,mo,y)=gettime()
    lcd12864.st(h,m,y+2000,mo,d,w)
    a=adc.read()
    sht31.sht31m(i2c)
    utime.sleep_ms(50)
    (t,h)=(sht31.sht31r(i2c))
    lcd12864.st1(t,h,a*6.5362/4096)

def gettime():
        da=i2c.readfrom_mem(81,2,8)
        s=((da[0]>>4) * 10) + (da[0]&0x0f)
        m=((da[1]>>4) * 10) + (da[1]&0x0f)
        h=((da[2]>>4) * 10) + (da[2]&0x0f)
        d=((da[3]>>4) * 10) + (da[3]&0x0f)
        w=((da[4]>>4) * 10) + (da[4]&0x0f)
        mo=((da[5]>>4) * 10) + (da[5]&0x0f)
        y=((da[6]>>4) * 10) + (da[6]&0x0f)
        return (s,m,h,d,w,mo,y)

if machine.wake_reason() == 0:
    led.off()
    lcd12864.lcdInit()
    lcd12864.print8("connect...",5,1)
    print("poweron")
    PFC8563.sync()
    showFast()


if machine.wake_reason() == 2:
    print("key")
    showFast()
if machine.wake_reason() == 4:
    showSlow()
    da=i2c.readfrom_mem(81,2,1)
    s=((da[0]>>4) * 10) + (da[0]&0x0f)
    print("timer")
    machine.deepsleep((60-s)*1000)
    



